import { defineStore } from 'pinia'
import { t } from '@/locale'
import { redirect, getToken } from '@/utils/common'
import { addCart, editCart, deleteCart, getCartList } from '@/addon/deposit/api/cart';

interface Cart {
    cartList: AnyObject
    totalNum: number
    totalMoney: number
    isRepeat: boolean
    orderId: any
}

const useCartStore = defineStore('depositCart', {
    state: (): Cart => {
        return {
            cartList: {}, // 购物车列表
            totalNum: 0, // 购物车商品总数量
            totalMoney: 0, // 购物车商品总价格
            orderId: undefined, //订单号
            isRepeat: false
        }
    },
    actions: {
        // 查询购物车列表
        getList(callback: any = null) {
            if (!getToken()) {
                // 每次查询清空
                for (let k in this.cartList) {
                    delete this.cartList[k];
                }
                this.totalNum = 0;
                this.totalMoney = 0;
                return;
            }
            getCartList({ useCase: 7 }).then((res: any) => {
                let data = res.data;

                // 每次查询清空
                for (let k in this.cartList) {
                    delete this.cartList[k];
                }
                if (data) {
                    this.orderId = data.no
                    data.validList.forEach((item: any) => {
                        console.log(item)
                        // item.spu.status == 1 && item.spu.delete_time == 0 &&
                        if (item.sku) {
                            let cart: any = {
                                id: item.id,
                                orderItemId: item.orderItemId,
                                no: item.no,
                                skuId: item.sku.skuId,
                                spuId: item.spu.spuId,
                                properties: item.sku.properties,
                                picUrl: item.sku.picUrl,
                                skuType: item.sku.skuType,
                                units: item.units,
                                employeeStr: item.employeeStr,
                                // num: item.count,
                                spuName: item.spu.spuName,
                                count: item.count,

                            };
                            if (!this.cartList['deposit_' + cart.orderItemId]) {
                                this.cartList['deposit_' + cart.orderItemId] = {};
                            }
                            this.cartList['deposit_' + cart.orderItemId]['sku_' + cart.orderItemId] = cart;
                        }
                    })
                }
                this.calculateNum();
                if (callback && typeof callback == 'function') callback();
            })
        },
        /**
         * 购物车数量增加
         * data：数据源
         * step：记步数量，默认为：1，每次加一个，设置为：0时，按照 num 修改
         */
        increase(data: any, step = 1, callback: any = null) {
            if (!data || (data && Object.keys(data).length == 0) || !data.orderItemId) return;
            if (!getToken()) return;

            let num = data.num || 0; // 当前数量
            let updateNum = num + step; // 变更数量

            let api = data.id ? editCart : addCart;

            if (this.isRepeat) return;
            this.isRepeat = true;
            // 更新存储数据
            if (data.id) {
                this.cartList['deposit_' + data.orderItemId]['sku_' + data.orderItemId].num = updateNum;
            } else {

                // 如果商品第一次添加，则初始化数据
                if (!this.cartList['deposit_' + data.orderItemId]) {
                    this.cartList['deposit_' + data.orderItemId] = {};
                }
                this.cartList['deposit_' + data.orderItemId]['sku_' + data.orderItemId] = {
                    orderItemId: data.orderItemId,
                    num: updateNum,
                };
            }

            this.calculateNum();

            api({
                id: data.id ? data.id : undefined,
                orderItemId: data.orderItemId,
                skuId: data.skuId,
                count: updateNum,
                useCase: data.useCase
            }).then(res => {
                this.getList(callback)
                this.isRepeat = false;
            }).catch(res => {
                this.isRepeat = false;
            })

        },
        /**
         * 购物车数量减少
         * data：数据源
         * step：记步数量，默认为：1，每次减一个，设置为：0时，按照 num 修改
         */
        reduce(data: any, step = 1, callback: any = null) {

            if (!data || (data && Object.keys(data).length == 0) || !data.orderItemId) return;
            if (!getToken()) return;

            let num = data.num || 0; // 当前数量
            let updateNum = num - step; // 变更数量

            let api = updateNum > 0 ? editCart : deleteCart;

            if (this.isRepeat) return;
            this.isRepeat = true;

            // 更新存储数据
            if (updateNum > 0) {
                this.cartList['deposit_' + data.orderItemId]['sku_' + data.orderItemId].num = updateNum;
            } else {
                delete this.cartList['deposit_' + data.orderItemId]['sku_' + data.orderItemId];
                if (Object.keys(this.cartList['deposit_' + data.orderItemId]).length == 0) delete this.cartList['deposit_' + data.orderItemId];
            }

            this.calculateNum();

            api({
                ids: data.id, // 删除接口用
                id: data.id,
                // spuId: data.spuId,
                // skuId: data.skuId,
                count: updateNum
            }).then(res => {
                this.getList(callback);
                this.isRepeat = false;
            }).catch(res => {
                this.isRepeat = false;
            })
        },

        // 购物车删除
        delete(ids: any, callback: any = null) {
            if (!ids) return;

            deleteCart({
                ids
            }).then(res => {
                this.getList();
                this.isRepeat = false;
                if (callback) callback();
            }).catch(res => {
                this.isRepeat = false;
            })
        },

        // 计算购物车商品的总数量、总价格
        calculateNum() {
            this.totalNum = 0;
            this.totalNum = Object.keys(this.cartList).length;

            // if (Object.keys(this.cartList).length) {
            //     for (let goods in this.cartList) {
            //         console.log(goods)
            //         let totalNum = 0;
            //         for (let sku in this.cartList[goods]) {
            //             if (typeof this.cartList[goods][sku] == 'object') {
            //                 totalNum += this.cartList[goods][sku].num;
            //             }
            //         }
            //         this.cartList[goods].totalNum = totalNum;


            //         this.totalNum += totalNum;

            //     }
            // }
        }
    }
})

export default useCartStore
